package com.losl.common.core.domain;

import cn.hutool.core.convert.Convert;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.losl.common.constant.PageConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.util.Date;

public class BaseController {
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    /**
     * 对日期数据进行处理
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        webDataBinder. registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtil.parse(text,parsePatterns));
            }
        });
    }

    public <T> Page<T> getPage() {
        return getPage(false);
    }

    public <T> Page<T> getPage(Boolean openSort){
        int index=1;
        /**
         * 页数
         */
        Integer cursor = Convert.toInt(request.getParameter(PageConst.PAGE_PAGE));
        /**
         * 分页大小
         */
        Integer limit = Convert.toInt(request.getParameter(PageConst.PAGE_LIMIT));
        /**
         * 是否分页
         */
        Boolean isPage = Convert.toBool(request.getParameter(PageConst.SEARCH_COUNT));

        limit=limit>PageConst.MAX_LIMIT?PageConst.MAX_LIMIT:limit;
        Page<T> page = new Page<>(cursor,limit,isPage);
        return page;
    }

}
